import time
import threading
from datetime import datetime
from data_feeds.manager import DataFeedManager
from common.data_models import TickData, DataType

class DataPressureTest:
    """数据压力测试套件"""
    
    def __init__(self):
        self.manager = DataFeedManager()
        self.test_results = {
            'total_ticks': 0,
            'max_tick_rate': 0,
            'min_tick_rate': float('inf'),
            'errors': 0,
            'start_time': None,
            'end_time': None
        }
        
    def high_frequency_test(self, duration: int = 30):
        """高频数据压力测试"""
        print(f"开始高频数据压力测试，持续时间: {duration}秒")
        
        # 创建数据源
        feed_id = self.manager.create_feed("mock", {})
        self.manager.connect(feed_id)
        feed = self.manager.feeds[feed_id]
        
        # 添加高性能回调
        feed.add_tick_callback(self._pressure_callback)
        
        # 订阅大量符号
        symbols = [f"SYMBOL_{i}" for i in range(20)]  # 20个符号
        self.manager.subscribe(feed_id, symbols, DataType.TICK)
        
        # 开始测试
        self.test_results['start_time'] = datetime.now()
        self._running = True
        
        # 监控线程
        monitor_thread = threading.Thread(target=self._monitor_test, args=(duration,))
        monitor_thread.start()
        
        # 等待测试完成
        monitor_thread.join()
        
        # 生成报告
        self._generate_report()
        
    def _pressure_callback(self, tick: TickData):
        """压力测试回调 - 模拟真实处理逻辑"""
        self.test_results['total_ticks'] += 1
        
        # 模拟一些数据处理
        _ = tick.symbol + str(tick.price)
        _ = tick.volume * 1000
        
        # 简单的错误注入测试
        if self.test_results['total_ticks'] % 1000 == 0:
            # 每1000个tick检查一次系统状态
            health = tick.price > 0  # 简单健康检查
            if not health:
                self.test_results['errors'] += 1
                
    def _monitor_test(self, duration: int):
        """监控测试进度"""
        start_time = time.time()
        last_count = 0
        last_check = start_time
        
        while time.time() - start_time < duration:
            current_time = time.time()
            elapsed = current_time - last_check
            
            if elapsed >= 1.0:  # 每秒计算一次速率
                current_count = self.test_results['total_ticks']
                tick_rate = (current_count - last_count) / elapsed
                
                self.test_results['max_tick_rate'] = max(self.test_results['max_tick_rate'], tick_rate)
                self.test_results['min_tick_rate'] = min(self.test_results['min_tick_rate'], tick_rate)
                
                print(f"当前速率: {tick_rate:.1f} ticks/秒 | 总Tick数: {current_count} | 错误: {self.test_results['errors']}")
                
                last_count = current_count
                last_check = current_time
                
            time.sleep(0.1)
            
        self.test_results['end_time'] = datetime.now()
        self._running = False
        
    def _generate_report(self):
        """生成压力测试报告"""
        duration = (self.test_results['end_time'] - self.test_results['start_time']).total_seconds()
        avg_rate = self.test_results['total_ticks'] / duration
        
        print("\n" + "="*50)
        print("数据压力测试报告")
        print("="*50)
        print(f"测试时长: {duration:.2f} 秒")
        print(f"总处理Tick数: {self.test_results['total_ticks']}")
        print(f"平均处理速率: {avg_rate:.1f} ticks/秒")
        print(f"最高处理速率: {self.test_results['max_tick_rate']:.1f} ticks/秒")
        print(f"最低处理速率: {self.test_results['min_tick_rate']:.1f} ticks/秒")
        print(f"错误数量: {self.test_results['errors']}")
        
        if self.test_results['total_ticks'] > 0:
            error_rate = (self.test_results['errors'] / self.test_results['total_ticks'] * 100)
            print(f"错误率: {error_rate:.4f}%")
        else:
            print(f"错误率: 0%")
        
        # 通过标准
        requirements_met = [
            avg_rate > 100,
            self.test_results['errors'] == 0,
            self.test_results['min_tick_rate'] > 50
        ]
        
        if all(requirements_met):
            print("🎉 压力测试: ✅ 通过")
        else:
            print("❌ 压力测试: 未通过")
            if avg_rate <= 100:
                print("  - 平均处理速率不足100 ticks/秒")
            if self.test_results['errors'] > 0:
                print("  - 存在处理错误")
            if self.test_results['min_tick_rate'] <= 50:
                print("  - 最低处理速率不足50 ticks/秒")

def main():
    """运行压力测试"""
    print("启动数据压力测试系统...")
    
    tester = DataPressureTest()
    tester.high_frequency_test(duration=10)  # 10秒测试
    
if __name__ == "__main__":
    main()